package com.yami.shop.security.common.config;

import cn.hutool.json.JSON;
import com.yami.shop.common.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
@Slf4j
public class WxHttpUtil {

/*    @Bean
    public RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //60s
        requestFactory.setConnectTimeout(60 * 1000);
        requestFactory.setReadTimeout(60 * 1000);
        return new RestTemplate(requestFactory);
    }*/

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }


    @Autowired
    private RestTemplate restTemplate;

    public String postForXml(String url, String xmlData) {
        String res = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "text/xml; charset=UTF-8");
            StringEntity se = new StringEntity(xmlData, "utf-8");
//			se.setContentType(MediaType.TEXT_XML_VALUE);
//			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE));
            httpPost.setEntity(se);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String value = response.getEntity().getContentType().getValue();
            log.info(value);
            byte[] bytes = null;
            // 读取图片字节数组
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = response.getEntity().getContent().read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            bytes = swapStream.toByteArray();
            res = new String(bytes, "utf-8");
            return res;

        } catch (IOException e) {
            log.error("postForXml异常", e);
            throw new RuntimeException("postForXml异常！");
        } finally {
            log.info("请求微信支付预付单url={},\nxmlData={},\nres={}", url, xmlData, res);
        }
    }


    private static final String APPLICATION_JSON = "application/json";
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";


    public <T> T wxGet(String url, HttpHeaders headers, Class<T> clazz) {
        ResponseEntity<T> response = null;
        try {
            HttpEntity<?> requestEntity;

            requestEntity = new HttpEntity<>(headers);
            response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, clazz);
            return response.getBody();
        } finally {
            log.info("wxGet 通用请求url={},\nresponse={}", url, Json.toJsonString(response));
        }
    }

    public <T> T wxPost(String url, String value, Class<T> clazz) {
        ResponseEntity<T> response = null;
        try {

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity requestEntity = new HttpEntity(value, headers);

//            HttpEntity<?> requestEntity;
//            requestEntity = new HttpEntity<>(value);
            response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, clazz);
            return response.getBody();
        } finally {
            log.info("wxPost 通用请求url={},\nbody={},\nresponse={}", url,value, Json.toJsonString(response));
        }
    }

    public <T> T wxUploadFile(String url, MultiValueMap<String, Object> value, Class<T> clazz) {
        ResponseEntity<T> response = null;
        try {

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.MULTIPART_FORM_DATA;
            //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity requestEntity = new HttpEntity(value, headers);

            response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, clazz);
            return response.getBody();
        } finally {
            log.info("wxPost 通用请求url={},\nbody={},\nresponse={}", url,value, Json.toJsonString(response));
        }
    }

}
